function ContractAdd_Code(id) {
	var date=new Date();
	var year=date.getFullYear()+1;
	var month=date.getMonth()+1;
	var day=date.getDate();
	var nearyear=(year+"-"+month+"-"+day).ToDate();
	var buffer = new StringBuffer();
	buffer.append('<div id="contractid" class="crmsheet border-bottom" val="'+id+'"><div class="ctitle"><div class="cname">合同编号</div><div class="require">*</div></div><div class="ctext"><input id="txt_num" type="text" placeholder="填写合同编号" value=""/></div><div class="carrow"></div></div>');
	buffer.append('<div id="signdate" class="crmsheet border-bottom date"><div class="ctitle"><div class="cname">签约日期</div><div class="require">*</div></div><div class="ctext"><input id="txt_signdate" type="text" readonly="readonly" placeholder="选择签约日期" value="'+date.Format("yyyy-MM-dd")+'"/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div id="selectorder" class="crmsheet border-bottom"><div class="ctitle"><div class="cname">选择订单</div><div class="require">*</div></div><div class="ctext"><input id="txt_orderid" orderid="" type="text" readonly="readonly" placeholder="选择订单" value=""/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">客户名称</div><div class="require">*</div></div><div class="ctext"><input id="txt_customerid" type="text" placeholder="选择完订单后自动显示" readonly="readonly" value=""/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">原始金额</div><div class="require">*</div></div><div class="ctext"><input id="txt_money" type="text" placeholder="选择完订单后自动显示" readonly="readonly" value=""/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">合同金额</div><div class="require">*</div></div><div class="ctext"><div class="money" style="width:50%"><input id="txt_dismoney" type="tel" placeholder="填写金额" value="" onkeyup="Check_Money(this);Cal_Discount();" onfocus="ScrollTop(this)"/></div><div class="money" style="width:30%"><input id="txt_hasdiscount" type="checkbox" onclick="Cal_Contract(this)" style="width:20px; background:gray;" /><label for="dismoney" style="width:35px;font-size:14px;">折扣</label></div><div class="money" style="width:20%"><input id="txt_percent" type="text" placeholder="折扣" value="100" disabled="disabled" style="text-align:right; color:#555555;" onkeyup="Check_Money(this);Cal_RoContract();" onfocus="ScrollTop()"/></div></div><div class="carrow">%</div></div>');
	buffer.append('<div class="crmsheet border-bottom date"><div class="ctitle"><div class="cname">开始日期</div><div class="require">*</div></div><div class="ctext"><input id="txt_begindate" touserid="" type="text" placeholder="选择开始日期" readonly="readonly" value="'+date.Format("yyyy-MM-dd")+'"/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom date"><div class="ctitle"><div class="cname">结束日期</div><div class="require">*</div></div><div class="ctext"><input id="txt_enddate" touserid="" type="text" placeholder="选择结束日期" readonly="readonly" value="'+nearyear+'"/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom users" show="1" touserid="'+User.ID+'"><div class="ctitle"><div class="cname">合同负责人</div><div class="require">*</div></div><div class="ctext"><input id="txt_headuser" touserid="'+User.ID+'" type="text" placeholder="选择合同负责人" readonly="readonly" value="'+User.RealName+'"/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom users" show="1" touserid="'+User.ID+'"><div class="ctitle"><div class="cname">我方签约人</div><div class="require">*</div></div><div class="ctext"><input id="txt_myman" touserid="'+User.ID+'" type="text" placeholder="选择我方签约人" readonly="readonly" value="'+User.RealName+'"/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">对方签约人</div><div class="require">*</div></div><div class="ctext"><input id="txt_otherman" touserid="" type="text" placeholder="填写对方签约人" value="" onfocus="ScrollTop()"/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">对方电话</div><div class="require">*</div></div><div class="ctext"><input id="txt_otherphone" touserid="" type="tel" placeholder="填写对方电话" value="" onfocus="ScrollTop()"/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">付款方式</div><div class="require">*</div></div><div class="ctext"><select id="txt_paytype"><option value="0">现金支付</option><option value="1">支付宝</option><option value="2">微信支付</option><option value="3">财付通</option><option value="4">网银转账</option><option value="5">支票</option><option value="6">邮政汇款</option><option value="7">电汇</option><option value="8">其他</option></select></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">合同类型</div></div><div class="ctext"><select id="txt_type"></select></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div id="selfcontent" val="'+id+'">');
	buffer.append('</div>');
	buffer.append('<div class="crmsheet border-bottom" style="height:120px;"><div class="ctitle"><div class="cname">订单备注</div></div><textarea id="txt_bak" placeholder="填写订单备注" onfocus="ScrollTop()"></textarea></div>');
	buffer.append('<div id="contact_tool" class="cline border-bottom"><font>展开更多</font></div>');
	buffer.append('<div id="contact_panel">');
	buffer.append('<div class="crmsheet border-bottom" style="height:120px;"><div class="ctitle"><div class="cname">合同正文</div></div><textarea id="txt_context" placeholder="填写合同正文"></textarea></div>');
	buffer.append('<div class="crmsheet border-bottom" style="height:120px;"><div class="ctitle"><div class="cname">产品说明</div></div><textarea id="txt_protxt" placeholder="填写产品说明"></textarea></div>');
	buffer.append('</div>');
	buffer.append('<div style="height:100px; float:left;"></div>');
	return buffer.toString();
};
function Cal_Discount() {
    var money = parseFloat($("#txt_money").val());
    var dismoney = parseFloat($("#txt_dismoney").val());
    if (!isNaN(dismoney)) {
        $("#txt_percent").val(ToDecimal(dismoney / money * 100));
    }
    if(money==dismoney)
    {
    	$("#txt_hasdiscount").prop("checked",false);
    }else
    {
    	$("#txt_hasdiscount").prop("checked",true);
    }
};

function Cal_RoContract() {
    var money = parseFloat($("#txt_money").val());
    var percent = parseFloat($("#txt_percent").val());
    $("#txt_dismoney").val(ToDecimal(money * percent / 100));
};
function Cal_Contract(o) {
    var ck = $(o).prop("checked");
    if (ck) {
        $("#txt_percent").removeAttr("disabled");
    } else {
        $("#txt_percent").attr("disabled", "disabled");
        $("#txt_dismoney").val($("#txt_money").val());
    }
    
    var money = parseFloat($("#txt_money").val());
    var dismoney = parseFloat($("#txt_dismoney").val());
    if (!isNaN(dismoney)) {
        $("#txt_percent").val(ToDecimal(dismoney / money * 100));
    }
};

var map;
var wsub;
var count=0;
var myScroll3;
function Init_ContractAdd(){
	var contractid=$("#contractid").attr("val");

		get("contact_tool").addEventListener("tap",function(){
			var state = $(this).find("font").html();
			if(state=="展开更多")
			{
				$("#contact_panel").show();
				$(this).find("font").html("关闭更多");
				$("#contentlist2").scrollTop(1000);
			}else
			{
				$("#contact_panel").hide();	
				$(this).find("font").html("展开更多");
			}
		});
	
	if(contractid!=0)
	{
		var data = {};
		data.act = "One_Contract";
		data.id=contractid;
		data.source=source;
		data.userid=userid;
		data.comid=comid;
		data.sign=GetSign(data.act);
		mui.getJSON(crm_domain, data, function (json) {
	            if (json.state) {
	                var contract=json.data.contract;
	                $("#txt_num").val(contract.Num);
	                $("#txt_orderid").attr("orderid",contract.POrderID);
	                $("#txt_orderid").val(contract.POrderNum);
	                $("#txt_customerid").attr("customerid",contract.CustomerID);
	                $("#txt_customerid").val(contract.CustomerName);
         			$("#txt_money").val(contract.Money);
        			$("#txt_dismoney").val(contract.DisMoney);
        			$("#txt_begindate").val(contract.BeginDate.ToDate());
        			$("#txt_enddate").val(contract.EndDate.ToDate());
        			$("#txt_headuser").attr("touserid",contract.HeadUser);
        			$("#txt_headuser").parent().parent().attr("touserid",contract.HeadUser);
        			$("#txt_headuser").val(contract.HeadUserName);
        			$("#txt_myman").attr("touserid",contract.MyMan);
        			$("#txt_myman").parent().parent().attr("touserid",contract.MyMan);
        			$("#txt_myman").val(contract.MyManName);
        			$("#txt_otherman").val(contract.OtherMan);
        			$("#txt_otherphone").val(contract.OtherPhone);
        			$("#txt_paytype").val(contract.PayType);
        			$("#txt_type").val(contract.Type);
        	
        			$("#txt_context").val(contract.Context);
        			$("#txt_protxt").val(contract.ProTxt);
        			$("#txt_hasdiscount").prop("checked",contract.HasDiscount);
        			if(contract.HasDiscount){
        				$("#txt_percent").removeAttr("disabled"); 
        			}
        			$("#txt_percent").val(contract.Percent);
        			$("#txt_signdate").val(contract.SignDate.ToDate());
	                Init_ContractTag(contract);
	            } else {
					plus.nativeUI.toast(json.msg);
	            }
	    });
    }else
    {
    	Init_ContractTag();
    }
	
	get("selectorder").addEventListener("tap",function(){
		myScroll3 = OpenScroll2(4,"选择订单","",function(pageindex){
										Receive_OrderSelect(pageindex);
								},function(){
									
								},OrderSelect_Code(),70);
								//$("#contentlist2").append(Publish_Code());
								Receive_OrderSelect(1);
								get("find2").addEventListener("tap",function(){
				      				$("#searchicon2").hide();
	      							$("#searchicons2").show();
	      							$("#keyword2").attr("placeholder","订单号，客户名称");
			    					if($("keyword2").val()!="")
			    					{
			    						//WorkMate_Search();
			    					}
				      			});
	});
	
	
	mui(".divmsg").on("tap",".users",function(){
			obj10=$(this);
			OpenWindow(4,"选择员工","确定",function(){
					var str1="",str2="",str3="",headimg="";
					touserid="";todepartid="";tocomid="";
	      			var count=0;
	      			mui.each(mui("#userlist input"),function(i,info){
	      				if(info.checked)
	      				{
	      					count++;
	      					touserid += info.value+",";
	      					str1 += info.getAttribute("val")+",";
	      				}
	      			});
	      			if(touserid.TrimEnd(",").split(",").length>1)
					{
						plus.nativeUI.toast("请选择1个");
						return;
					}
	      			obj10.find("input").val(str1.TrimEnd(","));
	      			obj10.find("input").attr("touserid",touserid.TrimEnd(","));
					obj10.attr("touserid",touserid.TrimEnd(","));
	      			CloseWindow();
			});
			
			$("#contentlist4").html(CheckMate_Data());
			data = {};
			data.act = "DepartAndUser_Data";
			data.userid=userid;
			data.comid=comid;
			data.source=source;
			data.sign=GetSign(data.act);
			
			mui.getJSON(admin_domain, data, function(json) {
				Bind_CheckMate(json.data.user,json.data.depart);
				Init_CheckMate();
				
			});
			if($(this).attr("show")=="1")
	      	{
	      		$(".selectbar").hide();
	      	}else
	      	{
				$(".selectbar").show();  				
	      	}
	    });
	    
	    mui(".divmsg").on("tap",".date",function(){
			obj10=this;
			var t=new Date();
			
			if($(this).find("input").val()!="")
			{
				var year_month_day=$(this).find("input").val().split("-");
				t.setFullYear(year_month_day[0]);
				t.setMonth(year_month_day[1]-1);
				t.setDate(year_month_day[2]);
			}
			plus.nativeUI.pickDate( function(e){
				var d=e.date;
				$(obj10).find("input").val((d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()).ToDate());
			},function(e){
				console.log( "未选择日期："+e.message );
			},{date:t});
		});
	
};

function Init_ContractTag(customer)
{
	var buffer = new StringBuffer();
	
	var data = {};
	data.act = "Contract_Tag";
	data.userid=userid;
	data.comid=comid;
	data.sign=GetSign(data.act);
	mui.getJSON(crm_domain, data, function(json) {
		$.each(json.data.taglist,function(i,info){
			if (info.Type == 1)
            {
			buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">'+info.Name+'</div>');
			if(info.IsRequired){
				buffer.append('<div class="require">*</div>');
			}
			buffer.append('</div><div class="ctext">');
			buffer.append('<select name="" class="select_new selftag" val="'+info.ColumnNum+'">');
                buffer.append('<option value="">选择'+info.Name+'</option>');
                $.each(info.TagDetail,function(k,detail)
                {
                	var isselect="";
                	if(customer){
                    if (info.ColumnNum == 1) { if (customer.Column1 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 2) { if (customer.Column2 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 3) { if (customer.Column3 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 4) { if (customer.Column4 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 5) { if (customer.Column5 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 6) { if (customer.Column6 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 7) { if (customer.Column7 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 8) { if (customer.Column8 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 9) { if (customer.Column9 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 10) { if (customer.Column10 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                   }
                	buffer.append('<option value="'+detail.Name+'" '+isselect +'>'+detail.Name+'</option>');
                });
                buffer.append('</select>');
			buffer.append('</div><div class="carrow"><img src="img/arrow.png"/></div></div>');
			}else{
			  var selftext = "";
			  if(customer){
              if (info.ColumnNum == 1) { selftext = customer.Column1; }
              if (info.ColumnNum == 2) { selftext = customer.Column2; }
              if (info.ColumnNum == 3) { selftext = customer.Column3; }
              if (info.ColumnNum == 4) { selftext = customer.Column4; }
              if (info.ColumnNum == 5) { selftext = customer.Column5; }
              if (info.ColumnNum == 6) { selftext = customer.Column6; }
              if (info.ColumnNum == 7) { selftext = customer.Column7; }
              if (info.ColumnNum == 8) { selftext = customer.Column8; }
              if (info.ColumnNum == 9) { selftext = customer.Column9; }
              if (info.ColumnNum == 10) { selftext = customer.Column10; }
              }
              buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">'+info.Name+'</div>');
              if(info.IsRequired){
              buffer.append('<div class="require">*</div>');
              }
              buffer.append('</div><div class="ctext"><input id="txt_name" type="text" class="selftag" placeholder="填写'+info.Name+'" value="'+selftext+'" val="'+info.ColumnNum+'"/></div></div>');
			}
		});
		$("#selfcontent").html(buffer.toString());
		
		buffer = new StringBuffer();
		$.each(json.data.type,function(i,info){
			buffer.append('<option value="'+info.Name +'">'+info.Name+'</option>');
		});
		$("#txt_type").html(buffer.toString());
		if(customer)
		{
			$("#txt_type").val(customer.Type);
		}
	});
};


function Save_Contract() {
	var txt_orderid = $("#txt_orderid");
    var txt_customerid = $("#txt_customerid");
    var data = {};
        data.act = "Save_Contract";
        data.id = $("#selfcontent").attr("val");
        data.userid=userid;
		data.comid=comid;
        data.porderid = txt_orderid.attr("orderid");
        data.pordernum = txt_orderid.val();
        data.customerid = txt_customerid.attr("customerid");
        data.customername = txt_customerid.val();
        data.num = $("#txt_num").val();
        data.money = $("#txt_money").val();
        data.dismoney = $("#txt_dismoney").val();
        data.begindate = $("#txt_begindate").val();
        data.enddate = $("#txt_enddate").val();
        data.headuser = $("#txt_headuser").attr("touserid");
        data.headusername = $("#txt_headuser").val();
        data.myman = $("#txt_myman").attr("touserid");
        data.mymanname = $("#txt_myman").val();
        data.otherman = $("#txt_otherman").val();
        data.otherphone = $("#txt_otherphone").val();
        data.paytype = $("#txt_paytype").val();
        data.type = $("#txt_type").val();
        data.annex = "";
        data.context = $("#txt_context").val();
        data.protxt = $("#txt_protxt").val();
        data.hasdiscount = $("#txt_hasdiscount").prop("checked");
        data.percent = $("#txt_percent").val();
        data.signdate = $("#txt_signdate").val();
        data.source = source; 
        data.version = version; 
        var selftag = new Array();
        $(".selftag").each(function () {
            selftag.push($(this).attr("val") + "*" + $(this).val());
        });
        data.selftag = selftag + "";
        data.sign=GetSign(data.act);
        if(data.num.Trim()=="")
        {
        	plus.nativeUI.toast("请填写合同编号");
        	return false;
        }
        if(data.porderid.Trim()=="")
        {
        	plus.nativeUI.toast("请选择订单");
        	return false;
        }
        if(data.dismoney.Trim()=="" || data.dismoney=="0")
        {
        	plus.nativeUI.toast("请填写合同金额");
        	return false;
        }
        if(data.headusername.Trim()=="")
        {
        	plus.nativeUI.toast("请选择合同负责人");
        	return false;
        }
        if(data.mymanname.Trim()=="")
        {
        	plus.nativeUI.toast("请选择我方签约人");
        	return false;
        }
        if(data.otherman.Trim()=="")
        {
        	plus.nativeUI.toast("请填写对方签约人");
        	return false;
        }
        if(data.otherphone.Trim()=="")
        {
        	plus.nativeUI.toast("请填写对方电话");
        	return false;
        }
        var error = false;
        $("#selfcontent .require").parent().parent().find(".selftag").each(function () {
            var tagname = this.tagName.toLowerCase();
            if ($(this).val().Trim()=="") {
            	
                if (tagname == "input") {
                    plus.nativeUI.toast($(this).attr("placeholder"));
                } else {
                    plus.nativeUI.toast("请" + $(this).find("option:first").html());
                }
                error = true;
                return false;
            }
        });
        if (error) {
            return;
        }
		plus.nativeUI.showWaiting( "正在保存..." );
        
		mui.getJSON(crm_domain, data, function (json) {
			plus.nativeUI.closeWaiting();
			plus.nativeUI.toast(json.msg);
            if (json.state) {
                CloseWindow();
                if(data.id==0)
                {
                	Clear_Form();
                	Contract_Search();
                }else{
                	Init_ContractDetail();
                	Contract_Search();
                }
                FindCrmReport();
            } 
        });
};

